import Handsontable from "handsontable";
import { undoManager, buildNewCellDef, checkSelection } from "../util/Utils.js";
import $ from "jquery";
const server = "https://auod-beijing.oss-cn-beijing.aliyuncs.com";

export default {
  builderImage (designer) {
    const { context } = designer;
    if (!checkSelection(context)) {
      return;
    }

    const hot = context.hot;
    const selected = hot.getSelected()[0];
    let startRow = selected[0];
    let startCol = selected[1];
    let endRow = selected[2];
    let endCol = selected[3];
    let tmp = endRow;
    if (startRow > endRow) {
      endRow = startRow;
      startRow = tmp;
    }
    tmp = endCol;
    if (startCol > endCol) {
      endCol = startCol;
      startCol = tmp;
    }
    let oldCellDef = context.getCell(startRow, startCol);
    let oldCellData = hot.getDataAtCell(startRow, startCol);
    let newCellDef = buildNewCellDef(startRow + 1, startCol + 1);
    newCellDef.value = {
      type: "image",
      source: "text",
      value: ""
    };
    context.addCell(newCellDef);
    const imagePath = server + "/ureport/icon/image.svg";
    const image = $(`<img src="${imagePath}" width="20px">`);
    const $td = $(hot.getCell(startRow, startCol));
    $td.empty();
    $td.append(image);
    context.isModify = true;
    Handsontable.hooks.run(hot, "afterSelectionEnd", startRow, startCol, endRow, endCol);

    const _this = this;
    undoManager.add({
      redo: function () {
        oldCellDef = _this.context.getCell(startRow, startCol);
        oldCellData = hot.getDataAtCell(startRow, startCol);
        newCellDef = buildNewCellDef(startRow + 1, startCol + 1);
        newCellDef.value = {
          type: "image",
          source: "text",
          value: ""
        };
        _this.context.addCell(newCellDef);
        hot.setDataAtCell(startRow, startCol, "");
        hot.render();
        context.isModify = true;
        Handsontable.hooks.run(hot, "afterSelectionEnd", startRow, startCol, endRow, endCol);
      },
      undo: function () {
        _this.context.addCell(oldCellDef);
        hot.setDataAtCell(startRow, startCol, oldCellData);
        hot.render();
        context.isModify = true;
        Handsontable.hooks.run(hot, "afterSelectionEnd", startRow, startCol, endRow, endCol);
      }
    });
  }
};
